package getip

import (
	"errors"
	"crypto/tls"
	"io/ioutil"
	"net/http"
	"regexp"
	"strings"

	log "ddns/log"
)

func GetIP(str []string) (Myip string) {
	m1 := make(map[string]int)
	var s2 []int
	var max int
	var s3 []string

	for _, v := range str {
		if m1[v] != 0 {
			m1[v]++
		} else {
			m1[v] = 1
		}
	}

	for _, v := range m1 {
		s2 = append(s2, v)
	}

	max = s2[0]
	for i := 0; i < len(s2); i++ {
		if max < s2[i] {
			max = s2[i]
		}
	}

	for k, v := range m1 {
		if v == max {
			s3 = append(s3, k)
		}
	}

	return s3[0]
}

func Process(webs []string) (ip string, err error) {
	var ips []string
	for _, weburl := range webs {
	        client := &http.Client{
                        Transport: &http.Transport{
                        TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
                        },
                }
		if !strings.HasPrefix(weburl, "http://") && !strings.HasPrefix(weburl, "https://") {
		// 如果不是，则添加 "http://" 前缀
		    weburl = "http://" + weburl
	        }
		//weburl := "http://" + web
		resp, err := client.Get(weburl)
		if err != nil {
			log.Errorf("from the web get ip error: %v\n", err)
			// fmt.Printf("get请求失败 error: %v\n", err)
			continue
		}
		defer resp.Body.Close()
		body, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			log.Errorf("read the body error: %v\n", err)
			// fmt.Printf("读取Body失败 error: %v\n", err)
			continue
		}
		regstr := `\d+\.\d+\.\d+\.\d+`   //两个及两个以上空格的正则表达式
		reg, _ := regexp.Compile(regstr) //编译正则表达式
		aaaaa := reg.Find([]byte(body))
		ips = append(ips, string(aaaaa))
		log.Debugf("Get ip from this web, web: %v, IP: %v\n", weburl, string(aaaaa))
	}

	ip = GetIP(ips)
	log.Debugf("The IP is: %v\n", ip)
	if len(ip) == 0 {
		var err error = errors.New("Get ip err")
		return "", err
	} else {
		return ip, nil
	}
}
